package com.soundShape.controllers.login
{
	import com.soundShape.constants.SoundShapeConstants;
	import com.soundShape.controllers.AbstractController;
	import com.soundShape.events.SoundShapeEvent;
	import com.soundShape.model.ApplicationModel;
	import com.soundShape.vo.EmployeeVO;
	
	import mx.collections.ArrayCollection;
	
	import nz.co.codec.flexorm.criteria.Criteria;

	public class LoginController extends AbstractController
	{
		
		[Inject]
		public var applicationModel:ApplicationModel;
		
		public function LoginController()
		{
		}
		
		[EventHandler(event="SoundShapeEvent.LOGIN")]
		public function doLogin(soundShapeEvent:SoundShapeEvent):void
		{
			trace(soundShapeEvent.data.alias + " " + soundShapeEvent.data.password);
			
			if(soundShapeEvent.data.alias == "" && soundShapeEvent.data.password == "")
			{
				trace("*** development login ***");
				doDevLogin();
				return;
			}
			
			var criteria:Criteria = applicationModel.entityManager.createCriteria(EmployeeVO);
			criteria.addEqualsCondition("alias",soundShapeEvent.data.alias);
			criteria.addEqualsCondition("password",soundShapeEvent.data.password);
			
			var employees:ArrayCollection = this.applicationModel.entityManager.fetchCriteria(criteria);
			
			var soundShapeEvent:SoundShapeEvent = new SoundShapeEvent(SoundShapeEvent.LOGIN_RESULT);
			
			if(employees.length == 0)
			{
				soundShapeEvent.data = {isValidLogin:false};
				this.dispatcher.dispatchEvent(soundShapeEvent);
			}
			else
			{
				this.applicationModel.employeeVO = employees.getItemAt(0) as EmployeeVO;
				soundShapeEvent.data = {isValidLogin:true};
				this.dispatcher.dispatchEvent(soundShapeEvent);
				
				//get customer list
				getCustomers();
			}
		}
		
		private function getCustomers():void
		{
			this.dispatcher.dispatchEvent(new SoundShapeEvent(SoundShapeEvent.GET_CUSTOMERS));
		}
		
		private function doDevLogin():void
		{
			
			var employeeVO:EmployeeVO = new EmployeeVO();
			employeeVO.alias = "dev";
			employeeVO.email = "mikecorbridge@gmail.com";
			employeeVO.employeeNum = "0";
			employeeVO.firstName = "Michael";
			employeeVO.lastName = "Corbridge";
			employeeVO.middleName = "D";
			employeeVO.password = "admin123";
			employeeVO.phoneNumber0 = "617.964.4529";
			employeeVO.phoneNumber1 = "617.242.0585";
			employeeVO.phoneNumber2 = "617.508.8898";
			employeeVO.role = SoundShapeConstants.ROLE_ADMINISTRATOR;
			employeeVO.userID = "developer00";
			
			this.applicationModel.employeeVO = employeeVO;
			
			
			var soundShapeEvent:SoundShapeEvent = new SoundShapeEvent(SoundShapeEvent.LOGIN_RESULT);
			soundShapeEvent.data = {isValidLogin:true};
			this.dispatcher.dispatchEvent(soundShapeEvent);
			
			getCustomers();
		}
		
	}
}